import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Лист материнский'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        product_up = None
        try:
            product = row["Первичный продукт"]
            steel_mark = row["Марка стали <Производство>"]
            strength = row["Класс прочности <Производство>"]
            if pd.isna(strength):
                strength=consolidator.strength_by_steel(steel_mark)
            strength_1 = consolidator.strength_mapping(strength,steel_mark)
            strength_led = consolidator.strength_led(strength_1[0])
            gmsps = consolidator.get_gmsps(steel_mark,"ТОЛСТЫЙ СЛЯБ") #специальное условие
            product_up = f"РАСКАТ {strength_led}"
            if "ГУ" in gmsps: product_up = "РАСКАТ ГУ"
            strength_led_int = int(strength_led[1:])
            thickness=row["Толщина раската, мм <Производство>"]
            print(f"{row['ID в SAP ERP VMZ']}:  strength: {strength}; strength_led_int: {strength_led_int}; thickness: {thickness}")
            if strength_led_int >= 60 : 
                thickness_range = consolidator.nearest_in_guid("Параметры по Продукту Прокат",
                    f"`Производство`=='Лист материнский' and `Продукт`=='РАСКАТ' and `Доп параметр2`=='{strength_led}'",
                    "Доп параметр1",
                    strength_led_int,
                    "Диапазон")
                product_up=f"РАСКАТ {thickness_range} {strength_led}"             
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__mother_sheet__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

